<template>
  <el-dialog 
    title="配置校验规则" 
    :visible.sync="dialogVisible"
    width="500px"
    append-to-body
    @closed="handleDialogClosed"
  >
    <el-form :model="localRule" label-width="120px" class="validate-form" ref="validateForm">
      <el-form-item label="是否必填">
        <el-switch 
          v-model="localRule.required" 
          active-text="是" 
          inactive-text="否"
          @change="handleRequiredChange"
        ></el-switch>
      </el-form-item>
      
      <el-form-item label="必填提示语" v-if="localRule.required">
        <el-input 
          v-model="localRule.requiredMsg" 
          size="mini" 
          placeholder="如：请填写屈服强度荷载"
          maxlength="50"
          show-word-limit
        ></el-input>
      </el-form-item>

      <!-- 数值类型配置 -->
      <template v-if="param && param.dataType === 'number'">
        <el-form-item label="数值最小值">
          <el-input-number
            v-model="localRule.min"
            size="mini"
            placeholder="如：0"
            :precision="getNumberPrecision(param)"
            :step="getStep(getNumberPrecision(param))"
            controls-position="right"
          ></el-input-number>
        </el-form-item>
        
        <el-form-item label="数值最大值">
          <el-input-number
            v-model="localRule.max"
            size="mini"
            placeholder="如：1000"
            :precision="getNumberPrecision(param)"
            :step="getStep(getNumberPrecision(param))"
            controls-position="right"
          ></el-input-number>
        </el-form-item>
        
        <el-form-item label="数值范围提示">
          <el-input 
            v-model="localRule.rangeMsg" 
            size="mini" 
            placeholder="如：荷载需在0-1000kN之间"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
      </template>

      <!-- 文本类型配置 -->
      <template v-if="param && param.dataType === 'text'">
        <el-form-item label="最小长度">
          <el-input-number
            v-model="localRule.minLength"
            size="mini"
            :min="0"
            :max="1000"
            placeholder="如：2"
            controls-position="right"
          ></el-input-number>
          <div class="config-tips">0表示不限制最小长度</div>
        </el-form-item>
        
        <el-form-item label="最大长度">
          <el-input-number
            v-model="localRule.maxLength"
            size="mini"
            :min="1"
            :max="4000"
            placeholder="如：50"
            controls-position="right"
          ></el-input-number>
          <div class="config-tips">最大支持4000个字符</div>
        </el-form-item>
        
        <el-form-item label="长度提示语">
          <el-input 
            v-model="localRule.lengthMsg" 
            size="mini" 
            placeholder="如：内容长度需在2-50个字符之间"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="正则表达式">
          <el-input 
            v-model="localRule.regex" 
            size="mini" 
            placeholder="如：^JG-\\d{4}-\\d{3}$"
          ></el-input>
          <div class="regex-tips">
            常用正则：<br>
            • 纯数字：^\d+$<br>
            • 样品编号：^[A-Z]{2}-\d{4}-\d{3}$<br>
            • 工程编号：^GC-\d{6}$<br>
            • 批次号：^BATCH-\d{8}$
          </div>
        </el-form-item>

        <el-form-item label="正则提示语" v-if="localRule.regex">
          <el-input 
            v-model="localRule.regexMsg" 
            size="mini" 
            placeholder="如：样品编号格式为JG-2024-001"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
      </template>

      <!-- 文本域类型配置 -->
      <template v-if="param && param.dataType === 'textarea'">
        <el-form-item label="最小长度">
          <el-input-number
            v-model="localRule.minLength"
            size="mini"
            :min="0"
            :max="10000"
            placeholder="如：10"
            controls-position="right"
          ></el-input-number>
          <div class="config-tips">0表示不限制最小长度</div>
        </el-form-item>
        
        <el-form-item label="最大长度">
          <el-input-number
            v-model="localRule.maxLength"
            size="mini"
            :min="1"
            :max="10000"
            placeholder="如：500"
            controls-position="right"
          ></el-input-number>
          <div class="config-tips">文本域最大支持10000个字符</div>
        </el-form-item>
        
        <el-form-item label="长度提示语">
          <el-input 
            v-model="localRule.lengthMsg" 
            size="mini" 
            placeholder="如：描述内容需在10-500个字符之间"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
      </template>

      <el-form-item label="日期范围" v-if="param && param.dataType === 'date'">
        <el-radio-group v-model="localRule.dateRangeType">
          <el-radio label="不限制"></el-radio>
          <el-radio label="不晚于当前日期"></el-radio>
          <el-radio label="自定义范围"></el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <!-- 配置预览 -->
    <div class="config-preview" v-if="hasConfig">
      <h4>配置预览：</h4>
      <div class="preview-content">
        <div v-if="localRule.required" class="preview-item">
          <el-tag type="success" size="mini">必填</el-tag>
          <span>{{ localRule.requiredMsg || '此字段为必填项' }}</span>
        </div>
        
        <div v-if="localRule.min !== '' || localRule.max !== ''" class="preview-item">
          <el-tag type="warning" size="mini">数值范围</el-tag>
          <span>{{ getNumberRangePreview() }}</span>
        </div>
        
        <div v-if="localRule.minLength || localRule.maxLength" class="preview-item">
          <el-tag type="info" size="mini">长度限制</el-tag>
          <span>{{ getLengthPreview() }}</span>
        </div>
        
        <div v-if="localRule.regex" class="preview-item">
          <el-tag type="danger" size="mini">格式验证</el-tag>
          <span>{{ localRule.regexMsg || '格式需符合正则表达式' }}</span>
        </div>
      </div>
    </div>

    <div slot="footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { cloneDeep } from 'lodash';

export default {
  name: 'ValidateRuleDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    rule: {
      type: Object,
      required: true,
      default: () => ({
        required: false,
        requiredMsg: '',
        min: '',
        max: '',
        rangeMsg: '',
        minLength: '',
        maxLength: '',
        lengthMsg: '',
        regex: '',
        regexMsg: '',
        dateRangeType: '不限制'
      })
    },
    param: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      localRule: this.getDefaultRule(),
      saving: false
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit('update:visible', value);
      }
    },
    // 是否有配置内容
    hasConfig() {
      return this.localRule.required || 
             this.localRule.min !== '' || 
             this.localRule.max !== '' || 
             this.localRule.minLength || 
             this.localRule.maxLength || 
             this.localRule.regex;
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        if (newVal) {
          this.initLocalRule();
        }
      },
      immediate: true
    },
    rule: {
      handler() {
        if (this.visible) {
          this.initLocalRule();
        }
      },
      deep: true
    }
  },
  methods: {
    // 获取默认规则
    getDefaultRule() {
      return {
        required: false,
        requiredMsg: '',
        min: '',
        max: '',
        rangeMsg: '',
        minLength: '',
        maxLength: '',
        lengthMsg: '',
        regex: '',
        regexMsg: '',
        dateRangeType: '不限制'
      };
    },

    // 初始化本地规则
    initLocalRule() {
      this.localRule = cloneDeep(this.rule) || this.getDefaultRule();
    },

    // 处理必填项变更
    handleRequiredChange(required) {
      if (required && !this.localRule.requiredMsg) {
        this.localRule.requiredMsg = '此字段为必填项';
      }
    },

    // 获取数字精度
    getNumberPrecision(param) {
      return param && param.precision !== undefined ? param.precision : 0;
    },

    // 获取步长
    getStep(precision) {
      if (precision === 0) return 1;
      if (precision === 1) return 0.1;
      if (precision === 2) return 0.01;
      return Math.pow(10, -precision);
    },

    // 获取数值范围预览
    getNumberRangePreview() {
      const { min, max, rangeMsg } = this.localRule;
      if (rangeMsg) return rangeMsg;
      
      if (min !== '' && max !== '') {
        return `数值范围：${min} ~ ${max}`;
      } else if (min !== '') {
        return `最小值：${min}`;
      } else if (max !== '') {
        return `最大值：${max}`;
      }
      return '';
    },

    // 获取长度预览
    getLengthPreview() {
      const { minLength, maxLength, lengthMsg } = this.localRule;
      if (lengthMsg) return lengthMsg;
      
      if (minLength && maxLength) {
        return `长度范围：${minLength} ~ ${maxLength} 个字符`;
      } else if (minLength) {
        return `最小长度：${minLength} 个字符`;
      } else if (maxLength) {
        return `最大长度：${maxLength} 个字符`;
      }
      return '';
    },

    // 处理保存
    handleSave() {
      this.saving = true;
      
      // 验证表单
      if (this.$refs.validateForm) {
        this.$refs.validateForm.validate((valid) => {
          if (valid) {
            // 清理空值
            const cleanedRule = this.cleanEmptyValues(this.localRule);
            this.$emit('save', cleanedRule);
            this.dialogVisible = false;
          } else {
            this.$message.warning('请完善校验规则配置');
          }
          this.saving = false;
        });
      } else {
        const cleanedRule = this.cleanEmptyValues(this.localRule);
        this.$emit('save', cleanedRule);
        this.dialogVisible = false;
        this.saving = false;
      }
    },

    // 清理空值
    cleanEmptyValues(rule) {
      const cleaned = cloneDeep(rule);
      Object.keys(cleaned).forEach(key => {
        if (cleaned[key] === '' || cleaned[key] === null || cleaned[key] === undefined) {
          delete cleaned[key];
        }
      });
      return cleaned;
    },

    // 处理取消
    handleCancel() {
      this.dialogVisible = false;
    },

    // 处理对话框关闭
    handleDialogClosed() {
      this.localRule = this.getDefaultRule();
      if (this.$refs.validateForm) {
        this.$refs.validateForm.clearValidate();
      }
    }
  }
};
</script>

<style scoped>
.validate-form {
  margin-top: 10px;
}

.validate-form .el-form-item {
  margin-bottom: 18px;
}

.config-tips {
  margin-top: 4px;
  font-size: 11px;
  color: #909399;
  line-height: 1.2;
}

.regex-tips {
  margin-top: 8px;
  font-size: 11px;
  color: #909399;
  background: #f5f7fa;
  padding: 8px;
  border-radius: 4px;
  line-height: 1.4;
}

.config-preview {
  margin-top: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.config-preview h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.preview-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preview-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #606266;
}

.preview-item .el-tag {
  flex-shrink: 0;
}
</style>